package com.rowenci.iot_agriculture.util.iot;

import com.rowenci.iot_agriculture.bean.Worker;
import com.rowenci.iot_agriculture.bean.admin.Loginlog;
import com.rowenci.iot_agriculture.bean.iot.Com;
import com.rowenci.iot_agriculture.bean.iot.Message;
import com.rowenci.iot_agriculture.bean.iot.Rfid;
import com.rowenci.iot_agriculture.service.api.ComService;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.rowenci.iot_agriculture.util.iot.SerialUtil.outputStream;

/**
 * <p>
 * 项目启动后执行下面
 * 接收阅读器串口发送来的数据并作出反应（向数据库中存储数据）
 * </p>
 *
 * @author rowenci
 * @date 2019/4/17 17:17
 */

/*@Component
@EnableAsync        // 2.开启多线程
@EnableScheduling   // 2.开启定时任务*/
public class SerialRFID {

    final String OPEN_AERIAL = "AA";
    final String CLOSE_AERIAL = "BB";

    @Resource
    private ComService comService;

    @Async
    @Scheduled(cron = "0/5 * * * * ?")
    public void configureTasks() throws Exception{

        System.out.println("开始打开阅读器");
        //因为阅读器是需要一直打开的，所以在这个全局任务当中，只打开sensor为reader的串口
        //获取阅读器串口
        List<Com> list = comService.findComBySensor("reader");

        //阅读器串口如果不存在 就一直循环查找
        while (list.isEmpty()) {
            System.out.println("阅读器串口不存在");
            list = comService.findComBySensor("reader");
            Thread.sleep(5000);
            if (!list.isEmpty()) {
                break;
            }
        }

        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                Com com = list.get(i);
                SerialUtil serial = new SerialUtil();
                int code = serial.startComPort(com);
                if (code == 1) {
                    //串口打开成功
                    System.out.println("阅读器打开成功:" + com.getComName());
                    try {
                        byte[] st = serial.hexStrToBinaryStr(OPEN_AERIAL);
                        System.out.println("发出字节数：" + st.length);
                        outputStream.write(st, 0, st.length);
                        serial.start();
                    } catch (IOException e) {
                        serial.closeSerial();
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}